package com.yupi.yuaicodemother.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yupi.yuaicodemother.exception.BusinessException;
import com.yupi.yuaicodemother.exception.ErrorCode;
import com.yupi.yuaicodemother.manager.CosManager;
import com.yupi.yuaicodemother.service.ScreenshotService;
import com.yupi.yuaicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;

    /**
     * 截图部署应用页面作为封面, 并上传至对象存储
     *
     * @param webUrl        网页 url
     * @return              返回对象存储 url
     */
    @Override
    public String generateAndUploadScreenshot(String webUrl) {

        // 参数校验
        if(StrUtil.isBlank(webUrl)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "网页 url 不能为空！");
        }
        log.info("开始生成网页截图，URL: {}", webUrl);

        // 截图并保存至本地
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);

        if(StrUtil.isBlank(localScreenshotPath)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "截图失败");
        }

        try {
            // 上传对象至对象存储
            String cosUrl = uploadScreenshotToCos(localScreenshotPath);
            if(StrUtil.isBlank(cosUrl)){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传图片失败！");
            }

            log.info("网页截图生成并上传成功: {} -> {}", webUrl, cosUrl);
            return cosUrl;
        } finally {
            // 清理本地文件
            cleanupLocalFile(localScreenshotPath);
        }
    }



    /**
     * 将本地截图上传至对象存储
     *
     * @param localScreenshotPath       本地截图 url
     * @return                          返回存储 url
     */
    private String uploadScreenshotToCos(String localScreenshotPath) {
        if(localScreenshotPath == null){
            return null;
        }

        File screenshotFile = new File(localScreenshotPath);

        if(!screenshotFile.exists()){
            log.error("截图文件不存在: {}", localScreenshotPath);
        }

        // 生成 COS 对象键
        String fileName = UUID.randomUUID().toString().substring(0, 8) + "_compressed.jpg";
        String cosKey = generateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey,screenshotFile);
    }

    /**
     * 生成截图的对象存储键
     * 格式：/screenshots/2025/07/31/filename.jpg
     */
    private String generateScreenshotKey(String fileName) {
        String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/mm/dd"));
        return String.format("/screenshots/%s/%s", datePath, fileName);
    }

    /**
     * 清理本地文件
     *
     * @param localFilePath 本地文件路径
     */
    private void cleanupLocalFile(String localFilePath) {
        File localFile = new File(localFilePath);
        if(localFile.exists()){
            File parentFile = localFile.getParentFile();
            FileUtil.del(parentFile);
            log.info("本地截图文件已清理: {}", localFilePath);
        }
    }
}
